package com.xc.stock.dto.query;

import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.ag.utils.CollectionUtils;
import com.ag.utils.Jsons;
import com.ag.utils.SysConstant;
import com.ag.utils.SysConstant.YesNoEnum;
import com.ag.utils.vo.TimeQuery;
import com.google.common.collect.Lists;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.Path;
import com.querydsl.core.types.Predicate;
import com.querydsl.core.types.dsl.BooleanExpression;
import com.xc.stock.infrastructure.db.po.QAccountPO;
import com.xc.stock.utils.ConditionBuilder;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

@Data
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@EqualsAndHashCode(callSuper = false)
public class AccountQuery extends TimeQuery {
	String accountNo;
	String accountNoList;
	String destId;
	String action;
	String search;
	String accountType;
	Integer status;
	Integer filterRemove;
	
	String orderSpecifier;
	public OrderSpecifier<?> orderSpecifier() {
		QAccountPO q = QAccountPO.accountPO;
		if ("idAsc".equals(orderSpecifier)) {
			return q.id.asc();
		}

		return q.id.desc();
	}
	
	public Predicate where() {
		return where(Lists.newArrayList());
	}
	
	public Predicate where(List<Path<?>> ignorePath) {
		super.check();
		QAccountPO q = QAccountPO.accountPO;
		ConditionBuilder builder = ConditionBuilder.builder();
		
		if(StringUtils.isNotBlank(search)) {
			BooleanExpression eq = q.destPhone.eq(search)
					.or(q.destId.eq(search));
			
			builder.and(eq);
		}
		
		if(StringUtils.isNotBlank(destId)) {
			builder.and(q.destId.eq(destId));
		}
		
		if(StringUtils.isNotBlank(accountNo)) {
			builder.and(q.accountNo.eq(accountNo));
		}
		
		if(CollectionUtils.isNotEmpty(Jsons.toListAnyway(accountNoList, String.class))) {
			builder.and(q.accountNo.in(Jsons.toList(accountNoList, String.class)));
		}
		
		if(StringUtils.isNotBlank(accountType)) {
			builder.and(q.accountType.eq(accountType));
		}
		
		if(status != null) {
			builder.and(q.status.eq(status));
		}
		
		if(YesNoEnum.isYes(filterRemove)) {
			builder.and(q.status.eq(SysConstant.STATUS_NORMAL));
		}
		
		if(dateStart() != null) {
			builder.and(q.createAt.between(dateStart(), dateEnd()));
		}

		return builder.build();
	}
}
